package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.AppointmentMapper;
import cn.wolfcode.car.business.query.AppointmentQuery;
import cn.wolfcode.car.business.service.IAppointmentService;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class AppointmentServiceImpl extends ServiceImpl<AppointmentMapper,Appointment> implements IAppointmentService {

    @Resource
    private AppointmentMapper appointmentMapper;
    @Autowired
    private IStatementService statementService;
    @Autowired
    private IStatementItemService statementItemService;

    @Override
    public TablePageInfo<Appointment> query(AppointmentQuery qo) {
        IPage<Appointment> page = new Page<>(qo.getPageNum(), qo.getPageSize());
        QueryWrapper<Appointment> wrapper = new QueryWrapper<>();
        wrapper.eq("idDel",0);
        wrapper.like(!qo.getCustomerName().trim().isEmpty(),"customerName",qo.getCustomerName());
        wrapper.like(!qo.getCustomerPhone().trim().isEmpty(),"customerPhone",qo.getCustomerPhone());
        wrapper.eq(qo.getStatus() != null,"status",qo.getStatus());
        return new TablePageInfo<>(super.page(page,wrapper));
    }


    @Override
    public boolean save(Appointment appointment) {
        appointment.setStatus(Appointment.STATUS_APPOINTMENT);
        appointmentMapper.insert(appointment);
        return true;
    }

    @Override
    public Appointment getById(Serializable id) {
        return appointmentMapper.selectById(id);
    }


    @Override
    public void update(Appointment appointment) {
        Appointment item = getById(appointment.getId());
        appointment.setStatus(item.getStatus());
        //状态不是预约中则不能编辑
        if (!item.getStatus().equals(Appointment.STATUS_APPOINTMENT)) {
            throw new BusinessException("亲，当前状态不是预约中，不能进行编辑操作");
        }
        appointmentMapper.updateById(appointment);
    }


    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        Integer idDel = 1;
        //dictId就是statementId
        for (Long dictId : dictIds) {
            // update bus_appointment set idDel = #{idDel} where id = #{id}
            UpdateWrapper<Appointment> wrapper = new UpdateWrapper<>();
            wrapper.eq("id",dictId);
            wrapper.set("idDel",idDel);
            appointmentMapper.update(null, wrapper);
            //delete from bus_statement_item where statement_id = #{statementId}
            statementItemService.deleteItemsByStatementId(dictId);
        }
    }


    @Override
    public List<Appointment> list() {
        return appointmentMapper.selectList(null);
    }

    @Override
    public void arrival(Long id, Integer statusArrival) {
        Appointment item = this.getById(id);
        //如果当前不是预约中状态则不可以点击到店
        if (!item.getStatus().equals(Appointment.STATUS_APPOINTMENT)) {
            throw new BusinessException("当前不是预约中，不可以进行到店操作");
        }
        //update bus_appointment set status = #{status} where id = #{id}
        LambdaUpdateWrapper<Appointment> wrapper = new LambdaUpdateWrapper();
        wrapper.eq(Appointment::getId,id);
        wrapper.set(Appointment::getStatus,statusArrival);
        appointmentMapper.update(null, wrapper);
        //update bus_appointment set actual_arrival_time = #{date} where id = #{id}   actual_arrival_time:到店的时间
        UpdateWrapper<Appointment> wrapper1 = new UpdateWrapper<>();
        wrapper1.eq("id",id);
        wrapper1.set("actual_arrival_time",new Date());
        appointmentMapper.update(null,wrapper1);
    }

    @Override
    public void cancel(Long id, Integer statusCancel) {
        Appointment item = this.getById(id);
        //如果当前不是预约中则不可以取消预约单
        if (!item.getStatus().equals(Appointment.STATUS_APPOINTMENT)) {
            throw new BusinessException("当前不是预约中状态，不可以取消该预约单");
        }
        LambdaUpdateWrapper<Appointment> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Appointment::getId,id);
        wrapper.set(Appointment::getStatus,statusCancel);
        ////update bus_appointment set status = #{status} where id = #{id}
        appointmentMapper.update(null,wrapper);
    }

    @Override
    public Statement generateStatement(Long appointmentId) {
        //获取预约中的对象
        Appointment appointment = this.getById(appointmentId);
        //如果不是已到店或者已结算 则不能点击结算单
        if (!(appointment.getStatus().equals(Appointment.STATUS_ARRIVAL) || appointment.getStatus().equals(Appointment.STATUS_SETTLE))) {
            throw new BusinessException("当前状态不是已到店或者已结算状态，不能进行结算单处理");
        }
        // select id, customer_name, customer_phone, actual_arrival_time, license_plate, car_series,
        //             service_type, appointment_id, status, pay_time, payee_id, total_amount, total_quantity,
        //             discount_amount, create_time, info
        //      from bus_statement where appointment_id = #{appointmentId}
        //通过查询预约id查询该结算单中有没有养修信息预约单中的相对应客户
        Statement statement = statementService.getByAppointment(appointmentId);
        if (statement == null) {
            //如果结算单中没有生成结算单消费记录，则生成结算单
            statement = new Statement();
            //关联预约单的id
            statement.setAppointmentId(appointmentId);
            //设置客户名称
            statement.setCustomerName(appointment.getCustomerName());
            //设置客户手机号码
            statement.setCustomerPhone(appointment.getCustomerPhone());
            //记录创建时间
            statement.setCreateTime(new Date());
            //设置到店时间
            statement.setActualArrivalTime(appointment.getActualArrivalTime());
            //设置车牌号
            statement.setLicensePlate(appointment.getLicensePlate());
            //设置汽车类型
            statement.setCarSeries(appointment.getCarSeries());
            //设置服务类型
            statement.setServiceType(Long.valueOf(appointment.getServiceType()));
            //设置备注信息
            statement.setInfo(appointment.getInfo());
            //插入到服务结算单中
            statementService.save(statement);
        }
        return statement;
    }

    @Override
    public void updateStatus(Long appointmentId, Integer statusSettle) {
        LambdaUpdateWrapper<Appointment> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Appointment::getId,appointmentId);
        wrapper.set(Appointment::getStatus,statusSettle);
        appointmentMapper.update(null,wrapper);
    }


}
